import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:management/const/consts.dart';
import 'package:management/const/flags.dart';
import 'package:management/const/icon.dart';
import 'package:management/const/init.dart';
import 'package:management/data/network/api/api.dart';
import 'package:management/data/network/entity/manage/people/ListMemberAndGroupResponse.dart';
import 'package:management/element/InputField.dart';
import 'package:management/element/loading.dart';
import 'package:management/element/toast.dart';
import 'package:management/main.dart';

import 'state.dart';

class GroupDetailScreenLogic extends GetxController {
  final GroupDetailScreenState state = GroupDetailScreenState();

  @override
  void onInit() {
    super.onInit();
    _initData();
  }

  Future<void> refreshGroupDetailPage() async {
    LoadingElement.loadingDialog(true);
    MyHttpClient.getCompanyMember(state.parentId.toString()).then((value) {
      if (value.code == 200) {
        state.listMember.value = value;
        state.listMember.refresh();
        Get.back();
      } else {
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Utils.toastError(error);
    });
  }

  void showEditSheet() {
    Get.bottomSheet(
        Wrap(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.symmetric(vertical: 2),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => _createCompanyMemberGroup(),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.createCompanyGroup.tr,
                      style: Theme.of(Get.context!).textTheme.bodyLarge,
                    ),
                  ],
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 5),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => Get.back(),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.cancel.tr,
                      style: Theme.of(Get.context!)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(color: MyColor.error),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        isDismissible: false,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  void jumpToPeopleDetail(Data? data) {
    Get.toNamed(RouteConfig.employeeDetailScreen,
        arguments: {'data': data?.id});
  }

  void jumpToNextGroup(Data? data) {
    Get.toNamed(RouteConfig.groupDetailScreen,
        arguments: {
          'id': data?.id,
          'name': data?.name,
          'permission': state.permission.value
        },
        preventDuplicates: false);
  }

  void _createCompanyMemberGroup() {
    Get.back();
    Get.defaultDialog(
        title: MyText.createCompanyGroup.tr,
        titleStyle: Theme.of(Get.context!).textTheme.titleSmall,
        content: MyTextField(
          prefixIcon: IconLight.Iconly_Light_Outline_Paper_Plus,
          isDark: Get.isDarkMode,
          hintText: MyText.companyGroupName.tr,
          onChanged: (value) {
            state.newCompanyGroupName = value;
          },
        ),
        contentPadding: const EdgeInsets.symmetric(horizontal: 20),
        onConfirm: () {
          MyHttpClient.createCompanyGroup(
                  state.newCompanyGroupName, state.parentId.value)
              .then((value) {
            if (value.code == 200) {
              Get.back();
              refreshGroupDetailPage();
            } else {
              Utils.toastError(value.msg);
            }
          }).onError((error, stackTrace) {
            Utils.toastError(error);
          });
        },
        textCancel: MyText.cancel.tr,
        textConfirm: MyText.confirm.tr);
  }

  ///////////////////////Group
  void groupOperateDialog(Data? data) {
    if (state.permission.value == CompanyMemberPermissions.member.toString()) {
      return;
    }
    if (data == null || data.name == null) {
      return;
    }
    if (data.type != "GROUP") {
      return;
    }
    Get.bottomSheet(
        Wrap(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.symmetric(vertical: 2),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => _deleteGroup(data),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.deleteCompanyGroup.tr,
                      style: Theme.of(Get.context!).textTheme.bodyLarge,
                    ),
                  ],
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(vertical: 2),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => _changeGroupName(data),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.changeCompanyGroup.tr,
                      style: Theme.of(Get.context!).textTheme.bodyLarge,
                    ),
                  ],
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(vertical: 2),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => _moveGroupPosition(data),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.mobileCompanyGroup.tr,
                      style: Theme.of(Get.context!).textTheme.bodyLarge,
                    ),
                  ],
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 5),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => Get.back(),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.cancel.tr,
                      style: Theme.of(Get.context!)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(color: MyColor.error),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        isDismissible: false,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  void _deleteGroup(Data data) {
    Get.back();
    Get.defaultDialog(
        title: MyText.deleteCompanyGroup.tr,
        titleStyle: Theme.of(Get.context!).textTheme.titleSmall,
        // titlePadding: const EdgeInsets.symmetric(horizontal: 20),
        content: Text(
          "${MyText.delete.tr}  ${data.name!}?",
          style: Theme.of(Get.context!).textTheme.bodyLarge,
        ),
        onConfirm: () {
          _realDeleteGroup(data);
          Get.back();
        },
        textCancel: MyText.cancel.tr,
        textConfirm: MyText.confirm.tr);
  }

  void _changeGroupName(Data data) {
    Get.back();
    Get.defaultDialog(
        title: MyText.changeCompanyGroup.tr,
        titleStyle: Theme.of(Get.context!).textTheme.titleSmall,
        content: MyTextField(
          prefixIcon: IconLight.Iconly_Light_Outline_Paper_Plus,
          isDark: Get.isDarkMode,
          hintText: MyText.companyGroupName.tr,
          onChanged: (value) {
            state.newCompanyGroupName = value;
          },
        ),
        onConfirm: () {
          MyHttpClient.changeCompanyGroup(
                  state.newCompanyGroupName, data.id.toString(), "")
              .then((value) {
            if (value.code == 200) {
              Get.back();
              refreshGroupDetailPage();
            } else {
              Utils.toastError(value.msg);
            }
          }).onError((error, stackTrace) {
            Utils.toastError(error);
          });
        },
        textCancel: MyText.cancel.tr,
        textConfirm: MyText.confirm.tr);
  }

  void _realDeleteGroup(Data data) {
    MyHttpClient.deleteCompanyGroup(data.id.toString()).then((value) {
      if (value.code == 200) {
        refreshGroupDetailPage();
      } else {
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Utils.toastError(error);
    });
  }

  void _moveGroupPosition(Data data) {
    Get.back();
    Get.toNamed(RouteConfig.groupLoadScreen, arguments: {
      'groupId': data.id,
      'isGroup': true,
      'groupName': data.name
    });
  }

  /////////////////////Employee
  void employeeOperateDialog(Data? data) {
    if (state.permission.value == CompanyMemberPermissions.member.toString()) {
      return;
    }
    if (data == null || data.nickname == null) {
      return;
    }
    Get.bottomSheet(
        Wrap(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.symmetric(vertical: 2),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => _deleteEmployee(data),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.deleteEmployee.tr,
                      style: Theme.of(Get.context!).textTheme.bodyLarge,
                    ),
                  ],
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(vertical: 2),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => _changeEmployee(data),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.changeEmployee.tr,
                      style: Theme.of(Get.context!).textTheme.bodyLarge,
                    ),
                  ],
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(vertical: 2),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => _moveEmployeePosition(data),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.mobileEmployeeGroup.tr,
                      style: Theme.of(Get.context!).textTheme.bodyLarge,
                    ),
                  ],
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 5),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => Get.back(),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.cancel.tr,
                      style: Theme.of(Get.context!)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(color: MyColor.error),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        isDismissible: false,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  void _deleteEmployee(Data data) {
    Get.back();
    Get.defaultDialog(
        title: MyText.deleteEmployee.tr,
        titleStyle: Theme.of(Get.context!).textTheme.titleSmall,
        // titlePadding: const EdgeInsets.symmetric(horizontal: 20),
        content: Text(
          "${MyText.fire.tr}  ${data.nickname!}?",
          style: Theme.of(Get.context!).textTheme.bodyLarge,
        ),
        onConfirm: () {
          _realDeleteEmployee(data);
          Get.back();
        },
        textCancel: MyText.cancel.tr,
        textConfirm: MyText.confirm.tr);
  }

  void _changeEmployee(Data data) {}

  void _moveEmployeePosition(Data data) {
    Get.back();
    Get.toNamed(RouteConfig.groupLoadScreen, arguments: {
      'groupId': data.id,
      'isGroup': false,
      'groupName': data.nickname
    });
  }

  void _realDeleteEmployee(Data data) {
    MyHttpClient.fireEmployee(data.id.toString()).then((value) {
      if (value.code == 200) {
        refreshGroupDetailPage();
      } else {
        Utils.toastError(value.msg);
      }
    }).onError((error, stackTrace) {
      Utils.toastError(error);
    });
  }

  void _initData() {
    String? refreshToken = GlobalInit.getSpData(SPFlag.refreshToken);
    MyHttpClient.getRefreshByToken(refreshToken!).then((value) {
      if (value.code == 200) {
        GlobalInit.saveSpData(SPFlag.expiresIn, value.data!.expiresIn!);
        GlobalInit.saveSpData(SPFlag.accessToken, value.data!.accessToken!);
        MyHttpClient.getCompanyMember(state.parentId.toString()).then((value) {
          if (value.code == 200) {
            state.listMember.value = value;
          } else {
            Utils.toastError(value.msg);
          }
        }).onError((error, stackTrace) {
          Utils.toastError(error);
        });
      }
    });
  }
}
